package jp.gr.java_conf.homeems.gw.internal.arduinopowermeter;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Random;

import jp.gr.java_conf.homeems.gw.measurementdatamanager.MeasurementDataBean;
import jp.gr.java_conf.homeems.gw.measurementdatamanager.MeasurementDataManagerService;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.util.tracker.ServiceTracker;

public class Activator implements BundleActivator {

	private static BundleContext context;

	private ServiceTracker<MeasurementDataManagerService, MeasurementDataManagerService> measurementDataManagerServiceTracker;
	
	static BundleContext getContext() {
		return context;
	}

	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext bundleContext) throws Exception {
		Activator.context = bundleContext;
		
		openServiceTracker(bundleContext);
		
		MeasurementDataManagerService measurementDataManagerService = this.measurementDataManagerServiceTracker.getService();
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		Random rnd = new Random();
		MeasurementDataBean measurementDataBean = new MeasurementDataBean(sdf.format(cal.getTime()), 1, (rnd.nextInt(1000) / 100.0));
		measurementDataManagerService.saveMeasurementData(measurementDataBean);
	}

	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext bundleContext) throws Exception {
		Activator.context = null;
		
		closeServiceTracker();
	}

	private void openServiceTracker(BundleContext context)
	{
		this.measurementDataManagerServiceTracker = new ServiceTracker<MeasurementDataManagerService, MeasurementDataManagerService>(context, MeasurementDataManagerService.class, null);
		this.measurementDataManagerServiceTracker.open();
	}
	
	private void closeServiceTracker()
	{
		if(this.measurementDataManagerServiceTracker != null)
		{
			this.measurementDataManagerServiceTracker.close();
			this.measurementDataManagerServiceTracker = null;
		}
	}
}
